/*
 * Copyright (c) 2014 - 2016. Danlu.com Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.coupon;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.base.DanluBaseActivity;
import cn.com.dhc.danlu.delegate.callback.ICouponListView;
import cn.com.dhc.danlu.delegate.delegate.coupon.DealersCouponObtainDelegate;
import cn.com.dhc.danlu.util.CommonConst.CouponConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.DanluCouponRecyclerView;
import cn.com.dhc.danlu.widget.couponview.CouponFilterPopupView;
import cn.com.dhc.danlu.widget.couponview.filterview.CouponFilterView;
import cn.com.dhc.danlu.widget.couponview.filterview.FilterType;
import cn.com.dhc.danlu.widget.couponview.filterview.OnFilterClickListener;
import cn.com.dhc.danlu.widget.loadlayer.LoaddingLayout;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.freedom.request.coupon.GetActivityListReq;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonUtils.getStatusBarHeight;

/**
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * author: 吴海洋(<a href="mailto:wuhiayang@danlu.com">wuhiayang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-09-19 10:21<br/>
 *
 * <p>
 * 领券中心 & 抢经销商红包
 * </p>
 */
public class DealersCouponObtainActivity extends DanluBaseActivity implements ICouponListView {
    // 通用请求参数 tips： 不要设置分页相关变量
    private final GetActivityListReq mRequestParams = new GetActivityListReq (agent.getToken ());
    // 基础交互控件
    private DanluCouponRecyclerView xrvCoupon;
    private LoaddingLayout llLoading;
    private CouponFilterView cfvFilter;  // 筛选功能栏
    private FilterType mFilterType;
    // 数据层+分页相关逻辑层
    private DealersCouponObtainDelegate mDelegate;
    private CouponFilterPopupView mFilterCouponPopup;
    private DealersCouponObtainAdapter adapter;

    public static void startSelf (Context context, Bundle bundle) {
        Intent intent = new Intent (context, DealersCouponObtainActivity.class);
        intent.putExtras (bundle);
        context.startActivity (intent);
    }

    // 数据交互回调
    @Override
    public BaseRequest createFetchReqParams () {
        return mRequestParams;
    }

    @Override
    public void onSuccess (@NonNull List datas, boolean isRefresh) {
        cfvFilter.canClickChildView (true);
        if (isRefresh) {
            //下拉刷新回调
            adapter.refreshAllData (datas);
            if (llLoading.isSuccessView ()) {
                // autorefresh | pullrefresh
                if (datas.isEmpty ()) {
                    llLoading.showEmptyView ();
                }
                xrvCoupon.refreshComplete ();
            } else {
                // click view mask | default
                if (datas.isEmpty ()) {
                    llLoading.showEmptyView ();
                } else {
                    llLoading.showContentView ();
                }
            }
        } else {
            if (datas.isEmpty ()) {
                ToastUtil.getInstance ().show ("没有更多数据");
                xrvCoupon.setNoMore (true);
            } else {
                adapter.appendData (datas);
            }
            xrvCoupon.loadMoreComplete ();
        }
    }

    @Override
    public void onError (@NonNull String errorInfo, boolean isRefresh) {
        cfvFilter.canClickChildView (true);
        if (isRefresh) {
            xrvCoupon.refreshComplete ();
            // clear all
            adapter.refreshAllData (new ArrayList ());
            llLoading.showErrorView (errorInfo);
        } else {
            ToastUtil.getInstance ().show (errorInfo);
            xrvCoupon.loadMoreComplete ();
        }
    }

    @Override
    protected void onCreate (@Nullable Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_coupon_obtain);

        if (null != savedInstanceState) {
            mFilterType = (FilterType) savedInstanceState.getSerializable (CouponConst.DEALERS_INTENT_TYPE);
        } else {
            mFilterType = (FilterType) getIntent ().getSerializableExtra (CouponConst.DEALERS_INTENT_TYPE);
        }

        initViews ();
        initApi ();
        setViews ();
        wrapDefaultValue ();
        callApiToLoad ();
    }

    private void initViews () {
        cfvFilter = (CouponFilterView) findViewById (R.id.cfv_filter);
        llLoading = (LoaddingLayout) findViewById (R.id.ll_loading);
        xrvCoupon = (DanluCouponRecyclerView) findViewById (R.id.xrv_coupon);

        cfvFilter.canClickChildView (false);
        xrvCoupon.setCouponFilterView (cfvFilter);
    }

    private void initApi () {
        mDelegate = new DealersCouponObtainDelegate ();
        mDelegate.attachHostView (this);
        mDelegate.setRefreshViewAttr (xrvCoupon);
    }

    private void setViews () {
        setLoaddingViewAttr ();
        switch (mFilterType) {
            case dealers_coupon:
                mToolbar.setTitle (R.string.dl_title_get_conpon);
                mToolbar.setRightTxt (R.string.dl_my_dealers_conpon);
                break;

            case dealers_envelop:
                mToolbar.setTitle (R.string.dl_title_rob_envelop);
                mToolbar.setRightTxt (R.string.my_envelop);
                break;

            default:
                break;
        }
        mToolbar.setRightClickListenter (new View.OnClickListener () {
            @Override
            public void onClick (View v) {
                DealersCouponUsedActivity.startSelf (DealersCouponObtainActivity.this, mFilterType);
            }
        });
        cfvFilter.setFilterType (mFilterType);
        cfvFilter.setOnFilterClickListener (new OnFilterClickListener () {
            @Override
            public void onDefaultCicked (View v) {

                mRequestParams.clearAllVariable ();
                if ((mFilterType == FilterType.dealers_coupon) && (null != mFilterCouponPopup)) {
                    mFilterCouponPopup.clearAllState ();
                }
                loadData ();
            }

            @Override
            public void onQuotaCicked (View v, String sortType) {
                mRequestParams.setSortField (CouponConst.DEALERS_SORT_ASC);
                mRequestParams.setSortType (sortType);
                loadData ();
            }

            @Override
            public void onDeadlineCicked (View v, String sortType) {
                mRequestParams.setSortField (CouponConst.DEALERS_SORT_DESC);
                mRequestParams.setSortType (sortType);
                loadData ();
            }

            @Override
            public void onFilterCicked (View v) {  // 点击筛选
                xrvCoupon.smoothScrollToPosition (0);
                xrvCoupon.setLoadingMoreEnabled (true);
                // 展开筛选界面
                showFilterMenu ();
            }
        });
        adapter = new DealersCouponObtainAdapter (DealersCouponObtainActivity.this, mFilterType);
        xrvCoupon.setAdapter (adapter);
        xrvCoupon.setRefreshView (mDelegate);
    }

    private void wrapDefaultValue () {
        switch (mFilterType) {
            case dealers_coupon:
                mRequestParams.setDealerCouponType (CouponConst.DEALERS_COUPON);
                break;

            case dealers_envelop:
                mRequestParams.setDealerCouponType (CouponConst.DEALERS_ENVELOPE);
                break;

            default:
                break;
        }
    }

    private void callApiToLoad () {
        xrvCoupon.scrollToPosition (0);
        cfvFilter.canClickChildView (false);
        if (!llLoading.isSuccessView ()) {
            llLoading.showLoaddingView ();
        } else {
            xrvCoupon.refresh ();
                }
        mDelegate.fetchData (true);
    }

    private void setLoaddingViewAttr () {
        llLoading.isShowEmptyRetryBtn (false);
        llLoading.changeEmptyViewTips (mFilterType == FilterType.dealers_coupon ? CommonUtils.getStringByResId (R.string.dl_coupon_empty) : CommonUtils.getStringByResId (R.string.dl_envelop_empty));
        llLoading.setEmptyPic (mFilterType == FilterType.dealers_coupon ? R.drawable.no_envelop : R.drawable.ic_empty_jxsenvelop);
        llLoading.setErrorViewRetryClickListener (new View.OnClickListener () {
            @Override
            public void onClick (View v) {
                llLoading.showLoaddingView ();
                callApiToLoad ();
            }
        });
    }

    protected void loadData () {
        xrvCoupon.scrollToPosition (0);
        xrvCoupon.setLoadingMoreEnabled (true);
        callApiToLoad ();
    }

    /**
     * 展开“筛选”弹窗页面
     */
    private void showFilterMenu () {
        ViewGroup decorView = (ViewGroup) getWindow ().getDecorView ();
        if (null == mFilterCouponPopup) {
            mFilterCouponPopup = new CouponFilterPopupView (this, decorView);
            mFilterCouponPopup.setNeedAnim (true);
            // 设置
            mFilterCouponPopup.setSureClickListener (new CouponFilterPopupView.ISureClickListener () {
                @Override
                public void onDataCallback (String categoryCode, String dealerName, String goodsName) {
                    if (TextUtils.isEmpty (goodsName) && TextUtils.isEmpty (dealerName) && TextUtils.isEmpty (categoryCode)) {
                        // 如果三者都为空，即可视为清空了所有条件，故此，高亮"默认"，且清除任何排序条件
                        mRequestParams.setSortField (null);
                        mRequestParams.setSortType (null);
                        mRequestParams.setMerchName (null);
                        mRequestParams.setDealerName (null);
                        mRequestParams.setCategoryCode (null);
                        // 高亮过滤条件栏
                        cfvFilter.setSelectState(cfvFilter.getDefaultView());
                    }
                    // 商品名
                    if (!TextUtils.isEmpty (goodsName)) {
                        mRequestParams.setMerchName (goodsName);
                    } else {
                        mRequestParams.setMerchName (null);
                    }
                    if (!TextUtils.isEmpty (dealerName)) {
                        mRequestParams.setDealerName (dealerName);
                    } else {
                        mRequestParams.setDealerName (null);
                    }
                    // 分类码
                    if (!TextUtils.isEmpty (categoryCode)) {
                        mRequestParams.setCategoryCode (categoryCode);
                    } else {
                        mRequestParams.setCategoryCode (null);
                    }
                    mFilterCouponPopup.dismiss ();
                    loadData ();
                }
            });
        }
        mFilterCouponPopup.showAtLocation (decorView, Gravity.CENTER, 0, getStatusBarHeight (DealersCouponObtainActivity.this));
    }

    @Override
    protected void onDestroy () {
        super.onDestroy ();
        mDelegate.detachHostView ();
    }

    @Override
    protected void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState (outState);
        outState.putSerializable (CouponConst.DEALERS_INTENT_TYPE, mFilterType);
    }

    @Override
    protected void onResume () {
        super.onResume ();
        callApiToLoad ();
    }
}
